<?php

namespace App\Http\Controllers\Wechat;

use App\Models\QrcodeString;
use App\Models\UserConnect;
use App\WeChat\WechatDefaultConfig;
use App\WeChat\WechatSubscribeHandler;
use EasyWeChat\Kernel\Messages\Message;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ServerController extends Controller
{
    use WechatDefaultConfig;

    public function index()
    {
        //验证时开启
        //$str = $this->request->input('echostr');
        //return response($str);
        $app = app('wechat.official_account');
        $app->server->push(function ($message){
            //return json_encode($message);
            //$connect = UserConnect::where('openid', $message['FormUserName']);
            $eventKey = str_replace('qrscene_', '', $message['EventKey']);
            $qs = QrcodeString::find($eventKey);
            if ($qs){
                if ($qs->type == 'invite')
                {
                    $newsitem = new NewsItem([
                        'title'=>'您好!请点击绑定账号信息!',
                        'description'=>'欢迎关注证品荟,请点击绑定账号信息!',
                        'url'=>url('h5/invite/bind?upuid='.$qs->uid),
                        'image'=>asset('images/h5/wellcome.jpg'),
                    ]);
                    return new News([$newsitem]);
                }
            }

            $newsitem = new NewsItem([
                'title'=>'欢迎关注证品荟!',
                'description'=>'欢迎关注证品荟!',
                'url'=>url('h5'),
                'image'=>asset('images/h5/wellcome.jpg'),
            ]);

            return new News([$newsitem]);
        }, Message::EVENT);

        return $app->server->serve();
    }
}
